using B.S.XZYData.Api.Wrter.Application.Command.ZSH;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.ZSH
{
	/// <summary>
	/// 新增不良品项处理器
	/// </summary>
	public class AddDefectiveHandler : IRequestHandler<AddDefectiveCommand, ApiResult<int>>
	{
		private readonly IBaseRepository<Defective> _repo;

		public AddDefectiveHandler(IBaseRepository<Defective> repo)
		{
			_repo = repo;
		}

		public async Task<ApiResult<int>> Handle(AddDefectiveCommand request, CancellationToken cancellationToken)
		{
			var result = new ApiResult<int>();

			// 名称必填，编号可选（为空则自动生成）
			if (string.IsNullOrWhiteSpace(request.DefectiveName))
			{
				result.Code = ApiEnum.Fail;
				result.Msg = "不良品项名称为必填";
				return await Task.FromResult(result);
			}

			// 编号处理：若为空则自动生成；若有值则校验唯一
			string code = request.DefectiveCode?.Trim();
			if (string.IsNullOrEmpty(code))
			{
				// 自动生成：BL + yyyyMMddHHmmssfff + 2位随机
				string GenCode() => $"BL{DateTime.Now:yyyyMMddHHmmssfff}{new Random().Next(10,99)}";
				code = GenCode();
				int guard = 0;
				while (_repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveCode == code) && guard < 5)
				{
					await Task.Delay(5, cancellationToken);
					code = GenCode();
					guard++;
				}
			}
			else
			{
				var codeExists = _repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveCode == code);
				if (codeExists)
				{
					result.Code = ApiEnum.Fail;
					result.Msg = "不良品项编号已存在";
					return await Task.FromResult(result);
				}
			}

			// 名称唯一校验
			var nameExists = _repo.GetAll().Any(x => !x.IsDeleted && x.DefectiveName == request.DefectiveName);
			if (nameExists)
			{
				result.Code = ApiEnum.Fail;
				result.Msg = "不良品项名称已存在";
				return await Task.FromResult(result);
			}

			var entity = new Defective
			{
				DefectiveCode = code,
				DefectiveName = request.DefectiveName,
				AttachmentPath = request.AttachmentPath,
				ImagePath = request.ImagePath,
				CreateTime = DateTime.Now,
				CreatorId = request.CreatorId,
				IsDeleted = false
			};

			var rows = await _repo.CreateAsync(entity);

			result.Code = rows > 0 ? ApiEnum.Success : ApiEnum.Fail;
			result.Msg = rows > 0 ? "新增成功" : "新增失败";
			result.Data = rows;
			return result;
		}
	}
}


